<!DOCTYPE html>

































































<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Services | Android Developers</title>
<link href="../../../assets/android-developer-docs-devguide.css" rel="stylesheet" type="text/css" />
<script src="../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../assets/android-developer-docs.js" type="text/javascript"></script>
<script src="../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
  setToRoot("../../../");
</script>
<noscript>
  <style type="text/css">
    html,body{overflow:auto;}
    #body-content{position:relative; top:0;}
    #doc-content{overflow:visible;border-left:3px solid #666;}
    #side-nav{padding:0;}
    #side-nav .toggle-list ul {display:block;}
    #resize-packages-nav{border-bottom:3px solid #666;}
  </style>
</noscript>
</head>
<body class="gc-documentation">

  <div id="header">
      <div id="headerLeft">
          <a href="../../../index.html" tabindex="-1"><img
              src="../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
          <ul id="header-tabs" class="guide">
    
	<li id="home-link"><a href="../../../offline.html">
	
		<span class="en">Home</span>
		<span style="display:none" class="de">Startseite</span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ホーム</span>
		<span style="display:none" class="zh-CN">主页</span>
		<span style="display:none" class="zh-TW">首頁</span>
	
	</a></li>
	<li id="sdk-link"><a href="../../../sdk/index.html">
		<span class="en">SDK</span>
	</a></li>
	<li id="guide-link"><a href="../../../guide/index.html" onClick="return loadLast('guide')">
	
		<span class="en">Dev Guide</span>
		<span style="display:none" class="de">Handbuch</span>
		<span style="display:none" class="es">Guía</span>
		<span style="display:none" class="fr">Guide</span>
		<span style="display:none" class="it">Guida</span>
		<span style="display:none" class="ja">開発ガイド</span>
		<span style="display:none" class="zh-CN">开发人员指南</span>
		<span style="display:none" class="zh-TW">開發指南</span>
	
	</a></li>
	<li id="reference-link"><a href="../../../reference/packages.html" onClick="return loadLast('reference')">
	
		<span class="en">Reference</span>
		<span style="display:none" class="de">Referenz</span>
		<span style="display:none" class="es">Referencia</span>
		<span style="display:none" class="fr">Référence</span>
		<span style="display:none" class="it">Riferimento</span>
		<span style="display:none" class="ja">リファレンス</span>
		<span style="display:none" class="zh-CN">参考</span>
		<span style="display:none" class="zh-TW">參考資料</span>
	
	</a></li>
	<li id="resources-link"><a href="../../../resources/index.html" onClick="return loadLast('resources')">
	
		<span class="en">Resources</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
    		<span style="display:none" class="ja"></span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li id="videos-link"><a href="../../../videos/index.html" onClick="return loadLast('videos')">
	
		<span class="en">Videos</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ビデオ</span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li><a href="http://android-developers.blogspot.com" onClick="return requestAppendHL(this.href)">
	
		<span class="en">Blog</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ブログ</span>
		<span style="display:none" class="zh-CN">博客</span>
		<span style="display:none" class="zh-TW">網誌</span>
	
	</a></li>


     
</ul>
     
      </div>
      <div id="headerRight">
          <div id="headerLinks">
          
          <a href="http://www.android.com">Android.com</a>
          </div>
  <div id="search" >
      <div id="searchForm">
          <form accept-charset="utf-8" class="gsc-search-box" 
                onsubmit="return submit_search()">
            <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
                <tr>
                  <td class="gsc-input">
                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../')"
                      onkeyup="return search_changed(event, false, '../../../')" />
                  <div id="search_filtered_div" class="no-display">
                      <table id="search_filtered" cellspacing=0>
                      </table>
                  </div>
                  </td>
                  <td class="gsc-search-button">
                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
                  </td>
                  <td class="gsc-clear-button">
                    <div title="clear results" class="gsc-clear-button">&nbsp;</div>
                  </td>
                </tr></tbody>
              </table>
          </form>
      </div><!-- searchForm -->
  </div><!-- search -->
      </div><!-- headerRight -->
      <script type="text/javascript">
        <!--  
        changeTabLang(getLangPref());
        //-->
      </script>
  </div><!-- header -->

  <div class="g-section g-tpl-240" id="body-content">
    <div class="g-unit g-first" id="side-nav">
      <div id="devdoc-nav">
<ul>

  <li>
    <h2><span class="en">Android Basics</span>
        <span class="de" style="display:none">Einführung in Android</span>
        <span class="es" style="display:none">Información básica sobre Android</span>
        <span class="fr" style="display:none">Présentation d'Android</span>
        <span class="it" style="display:none">Nozioni di base su Android</span>
        <span class="ja" style="display:none">Android の基本</span>
        <span class="zh-CN" style="display:none">Android 基础知识</span>
        <span class="zh-TW" style="display:none">Android 簡介</span>
    </h2>
    <ul>
      <li><a href="../../../guide/basics/what-is-android.html">
        <span class="en">What Is Android?</span>
        <span class="de" style="display:none">Was ist Android?</span>
        <span class="es" style="display:none">¿Qué es Android?</span>
        <span class="fr" style="display:none">Qu'est-ce qu'Android&nbsp;?</span>
        <span class="it" style="display:none">Che cos'è Android?</span>
        <span class="ja" style="display:none">Android とは</span>
        <span class="zh-CN" style="display:none">Android 是什么？</span>
        <span class="zh-TW" style="display:none">什麼是 Android？</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals.html">
        <span class="en">Application Fundamentals</span>
        <span class="de" style="display:none">Anwendungsgrundlagen</span>
        <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
        <span class="fr" style="display:none">Principes de base des applications</span>
        <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
        <span class="ja" style="display:none">開発の基礎</span>
        <span class="zh-CN" style="display:none">应用程序基础</span>
        <span class="zh-TW" style="display:none">應用程式基本原理</span>
      </a></li>

  <!--  <li><a style="color:gray;">The Android SDK</a></li> -->
  <!--  <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
      <!-- quick overview of what it's like to develop on Android -->
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Framework Topics</span>
      <span class="de" style="display:none">Framework-Themen</span>
      <span class="es" style="display:none">Temas sobre el framework</span>
      <span class="fr" style="display:none">Thèmes relatifs au framework</span>
      <span class="it" style="display:none">Argomenti relativi al framework</span>
      <span class="ja" style="display:none">フレームワーク トピック</span>
      <span class="zh-CN" style="display:none">框架主题</span>
      <span class="zh-TW" style="display:none">架構主題</span>
    </h2>
    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/activities.html">
          <span class="en">Activities</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/fragments.html">
            <span class="en">Fragments</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/loaders.html">
            <span class="en">Loaders</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">
            <span class="en">Tasks and Back Stack</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/services.html">
          <span class="en">Services</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/bound-services.html">
            <span class="en">Bound Services</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/topics/providers/content-providers.html">
            <span class="en">Content Providers</span>
          </a></li>
      <li><a href="../../../guide/topics/intents/intents-filters.html">
            <span class="en">Intents and Intent Filters</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals/processes-and-threads.html">
            <span class="en">Processes and Threads</span>
          </a></li>
    </ul>


    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/ui/index.html">
            <span class="en">User Interface</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/ui/declaring-layout.html">
               <span class="en">XML Layouts</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/ui-events.html">
                <span class="en">Input Events</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/menus.html">
               <span class="en">Menus</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/actionbar.html">
               <span class="en">Action Bar</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/dialogs.html">
                <span class="en">Dialogs</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/ui/notifiers/index.html">
                <span class="en">Notifications</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/ui/notifiers/toasts.html">
                <span class="en">Toast Notifications</span>
              </a></li>
              <li><a href="../../../guide/topics/ui/notifiers/notifications.html">
                <span class="en">Status Bar Notifications</span>
              </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/topics/ui/drag-drop.html">
                <span class="en">Drag and Drop</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/themes.html">
                <span class="en">Styles and Themes</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/custom-components.html">
                <span class="en">Custom Components</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/binding.html">
                <span class="en">Binding to Data with AdapterView</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/layout-objects.html">
                <span class="en">Common Layout Objects</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/how-android-draws.html">
                <span class="en">How Android Draws Views</span>
              </a></li>
        </ul>
      </li><!-- end of User Interface -->

      <li class="toggle-list">
        <div><a href="../../../guide/topics/resources/index.html">
               <span class="en">Application Resources</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/resources/providing-resources.html">
                <span class="en">Providing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/accessing-resources.html">
                <span class="en">Accessing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/runtime-changes.html">
                <span class="en">Handling Runtime Changes</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/localization.html">
                <span class="en">Localization</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/resources/available-resources.html">
              <span class="en">Resource Types</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li>
              <li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li>
              <li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li>
              <li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li>
              <li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li>
              <li><a href="../../../guide/topics/resources/string-resource.html">String</a></li>
              <li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li>
              <li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li>
            </ul>
          </li><!-- end of resource types -->
        </ul>
      </li><!-- end of app resources -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/data/data-storage.html">
            <span class="en">Data Storage</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/data/backup.html">
                <span class="en">Data Backup</span>
              </a>
            </li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/security/security.html">
            <span class="en">Security and Permissions</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/manifest/manifest-intro.html">
          <span class="en">The AndroidManifest.xml File</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/application-element.html">&lt;application&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/category-element.html">&lt;category&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/compatible-screens-element.html">&lt;compatible-screens&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/data-element.html">&lt;data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
        </ul>
      </li><!-- end of the manifest file -->
    </ul>

    <ul>
    <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/index.html">
            <span class="en">Graphics</span>
          </a><span class="new-child">new!</span></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/2d-graphics.html">
              <span class="en">Canvas and Drawables</span></a></li>
          <li><a href="../../../guide/topics/graphics/hardware-accel.html">
              <span class="en">Hardware Acceleration</span></a>
            <span class="new">new!</span></li>
          <li><a href="../../../guide/topics/graphics/opengl.html">
              <span class="en">OpenGL</span>
            </a><span class="new">updated</span></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/animation.html">
            <span class="en">Animation</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/prop-animation.html">
              <span class="en">Property Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/view-animation.html">
              <span class="en">View Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/drawable-animation.html">
              <span class="en">Drawable Animation</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
	        <div><a href="../../../guide/topics/renderscript/index.html">
	            <span class="en">RenderScript</span>
	          </a></div>
	        <ul>
	          <li><a href="../../../guide/topics/renderscript/graphics.html">
	                <span class="en">Graphics</span>
	              </a>
	          </li>
	          <li><a href="../../../guide/topics/renderscript/compute.html">
	                <span class="en">Compute</span>
	              </a>
	          </li>
	        </ul>
  	  </li>

      <li class="toggle-list">
          <div><a href="../../../guide/topics/media/index.html">
            <span class="en">Multimedia and Camera</span>
          </a><span class="new">updated</span></div>
          <ul>
            <li><a href="../../../guide/topics/media/mediaplayer.html">
                  <span class="en">Media Playback</span></a>
                </li>
            <li><a href="../../../guide/topics/media/jetplayer.html">
                  <span class="en">JetPlayer</span></a>
                </li>
            <li><a href="../../../guide/topics/media/camera.html">
                  <span class="en">Camera</span></a>
                  <span class="new">new!</span>
                </li>
            <li><a href="../../../guide/topics/media/audio-capture.html">
                  <span class="en">Audio Capture</span></a>
                </li>
          </ul>
      </li>
      <li>
        <a href="../../../guide/topics/clipboard/copy-paste.html">
            <span class="en">Copy and Paste</span>
        </a></li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Sensors</a></div>
          <ul>
            <li><a style="color:gray;">Camera</a></li>
            <li><a style="color:gray;">Compass</a></li>
            <li><a style="color:gray;">Accelerometer</a></li>
          </ul>
      </li> -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/location/index.html">
               <span class="en">Location and Maps</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/location/obtaining-user-location.html">
                <span class="en">Obtaining User Location</span>
              </a></li>
        </ul>
      </li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Wireless Controls</a></div>
          <ul>
            <li><a style="color:gray;">Wi-Fi</a></li>
          </ul>
      </li> -->
  <!--<li><a style="color:gray;">Localization</a></li>  -->
      <li><a href="../../../guide/topics/appwidgets/index.html">
            <span class="en">App Widgets</span></a>
          </li>
      <li><a href="../../../guide/topics/wireless/bluetooth.html">
            <span class="en">Bluetooth</span></a>
          </li>
      <li><a href="../../../guide/topics/nfc/index.html">
            <span class="en">Near Field Communication</span>
          </a></li>
      <li class="toggle-list">
          <div><a href="../../../guide/topics/usb/index.html">
            <span class="en">USB</span></a>
          </div>
            <ul>
              <li><a href="../../../guide/topics/usb/accessory.html">Accessory</a></li>
              <li><a href="../../../guide/topics/usb/host.html">Host</a></li>
              <li><a href="../../../guide/topics/usb/adk.html">Open Accessory Dev Kit</a></li>
            </ul>
          </li>

       <li><a href="../../../guide/topics/network/sip.html">
            <span class="en">Session Initiation Protocol</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/search/index.html">
            <span class="en">Search</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li>
            <li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
            <li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
            <li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/admin/device-admin.html">
            <span class="en">Device Administration</span></a>
      </li>
      <li class="toggle-list">
           <div>
                <a href="../../../guide/topics/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/topics/testing/testing_android.html">
                <span class="en">Testing Fundamentals</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/activity_testing.html">
                <span class="en">Activity Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/contentprovider_testing.html">
                <span class="en">Content Provider Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/service_testing.html">
                <span class="en">Service Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/what_to_test.html">
                <span class="en">What To Test</span></a>
              </li>
           </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Android Market Topics</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/licensing.html">
          <span class="en">Application Licensing</span></a>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/market/billing/index.html">
            <span class="en">In-app Billing</span></a>
        </div>
        <ul>
          <li><a href="../../../guide/market/billing/billing_overview.html">
              <span class="en">In-app Billing Overview</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_integrate.html">
              <span class="en">Implementing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_best_practices.html">
              <span class="en">Security and Design</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_testing.html">
              <span class="en">Testing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_admin.html">
              <span class="en">Administering In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_reference.html">
              <span class="en">In-app Billing Reference</span></a>
          </li>
        </ul>
      </li>
      <li><a href="../../../guide/appendix/market-filters.html">
          <span class="en">Market Filters</span></a>
      </li>
      <li><a href="../../../guide/market/publishing/multiple-apks.html">
          <span class="en">Multiple APK Support</span></a>
      </li>
    </ul>
  </li>


  <li>
    <h2><span class="en">Developing</span>
               <span class="de" style="display:none">Entwicklung</span>
               <span class="es" style="display:none">Desarrollo</span>
               <span class="fr" style="display:none">Développement</span>
               <span class="it" style="display:none">Sviluppo</span>
               <span class="ja" style="display:none">開発</span>
               <span class="zh-CN" style="display:none">开发</span>
               <span class="zh-TW" style="display:none">開發</span>
    </h2>
    <ul>
  <!--<li><a href="">Developing for Android</a></li>
      signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. -->
      <li>
        <a href="../../../guide/developing/index.html">
        <span class="en">Introduction</span></a>
      </li>

      <li class="toggle-list">
        <div>
           <a href="../../../guide/developing/devices/index.html">
                <span class="en">Managing Virtual Devices</span>
            </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/devices/managing-avds.html">
              <span class="en">With AVD Manager</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/devices/managing-avds-cmdline.html">
              <span class="en">From the Command Line</span>
            </a>
          </li>
          <li>
           <a href="../../../guide/developing/devices/emulator.html">
                <span class="en">Using the Android Emulator</span>
            </a>
          </li>
        </ul>
      </li>
      <li>
        <a href="../../../guide/developing/device.html">
          <span class="en">Using Hardware Devices</span>
        </a>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/projects/index.html">
            <span class="en">Managing Projects</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/projects/projects-eclipse.html">
              <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/projects/projects-cmdline.html">
                <span class="en">From the Command Line</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/building/index.html">
            <span class="en">Building and Running</span>
          </a>
        </div>
        <ul>
          <li><a href="../../../guide/developing/building/building-eclipse.html">
            <span class="en">From Eclipse with ADT</span>
          </a></li>
          <li><a href="../../../guide/developing/building/building-cmdline.html">
            <span class="en">From the Command Line</span></a></li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/debugging/index.html">
            <span class="en">Debugging</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects.html">
                <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects-cmdline.html">
                <span class="en">From Other IDEs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/ddms.html">
              <span class="en">Using DDMS</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-log.html">
                <span class="en">Reading and Writing Logs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-ui.html">
                <span class="en">Debugging and Profiling UIs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-tracing.html">
                <span class="en">Profiling with Traceview and dmtracedump</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-devtools.html">
                <span class="en">Using the Dev Tools App</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
           <div>
                <a href="../../../guide/developing/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/developing/testing/testing_eclipse.html">
                  <span class="en">From Eclipse with ADT</span>
                </a>
              </li>

              <li>
                <a href="../../../guide/developing/testing/testing_otheride.html">
                  <span class="en">From Other IDEs</span>
                </a>
              </li>
           </ul>
         </li>

         <li class="toggle-list">
        <div><a href="../../../guide/developing/tools/index.html">
            <span class="en">Tools</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/developing/tools/adb.html">adb</a></li>
          <li><a href="../../../guide/developing/tools/adt.html">ADT</a></li>
          <li><a href="../../../guide/developing/tools/android.html">android</a></li>
          <li><a href="../../../guide/developing/tools/bmgr.html">bmgr</a>
          <li><a href="../../../guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
          <li><a href="../../../guide/developing/tools/draw9patch.html">Draw
          9-Patch</a></li>
          <li><a href="../../../guide/developing/tools/emulator.html">Emulator</a></li>
          <li><a href="../../../guide/developing/tools/etc1tool.html">etc1tool</a></li>
          <li><a href="../../../guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li>
          <li><a href="../../../guide/developing/tools/hprof-conv.html">hprof-conv</a></li>
          <li><a href="../../../guide/developing/tools/layoutopt.html">layoutopt</a></li>
          <li><a href="../../../guide/developing/tools/logcat.html">logcat</a></li>
          <li><a href="../../../guide/developing/tools/mksdcard.html">mksdcard</a></li>
          <li><a href="../../../guide/developing/tools/monkey.html">Monkey</a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/developing/tools/monkeyrunner_concepts.html">
              <span class="en">monkeyrunner</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/developing/tools/MonkeyDevice.html">
                <span class="en">MonkeyDevice</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyImage.html">
                <span class="en">MonkeyImage</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyRunner.html">
                <span class="en">MonkeyRunner</span>
                </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/developing/tools/proguard.html">ProGuard</a></li>
          <li><a href="../../../guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
          <li><a href="../../../guide/developing/tools/traceview.html">Traceview</a></li>
          <li><a href="../../../guide/developing/tools/zipalign.html">zipalign</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Publishing</span>
        <span class="de" style="display:none">Veröffentlichung</span>
        <span class="es" style="display:none">Publicación</span>
        <span class="fr" style="display:none">Publication</span>
        <span class="it" style="display:none">Pubblicazione</span>
        <span class="ja" style="display:none">公開</span>
        <span class="zh-CN" style="display:none">发布</span>
        <span class="zh-TW" style="display:none">發佈</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/app-signing.html">
            <span class="en">Signing Your Applications</span>
            <span class="de" style="display:none">Signieren Ihrer Anwendungen</span>
            <span class="es" style="display:none">Firma de aplicaciones</span>
            <span class="fr" style="display:none">Attribution de votre signature <br />à vos applications</span>
            <span class="it" style="display:none">Firma delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションへの署名</span>
            <span class="zh-CN" style="display:none">应用程序签名</span>
            <span class="zh-TW" style="display:none">簽署應用程式</span>
          </a></li>
      <li><a href="../../../guide/publishing/versioning.html">
            <span class="en">Versioning Your Applications</span>
            <span class="de" style="display:none">Versionsverwaltung für Ihre <br />Anwendungen</span>
            <span class="es" style="display:none">Versiones de las aplicaciones</span>
            <span class="fr" style="display:none">Attribution d'une version à vos applications</span>
            <span class="it" style="display:none">Controllo versioni delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションのバージョニング</span>
            <span class="zh-CN" style="display:none">应用程序版本控制</span>
            <span class="zh-TW" style="display:none">應用程式版本設定</span>
          </a></li>
      <li><a href="../../../guide/publishing/preparing.html">
            <span class="en">Preparing to Publish</span>
            <span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
            <span class="es" style="display:none">Publicación de aplicaciones</span>
            <span class="fr" style="display:none">Préparation à la publication</span>
            <span class="it" style="display:none">Preparativi per la pubblicazione</span>
            <span class="ja" style="display:none">公開の準備</span>
            <span class="zh-CN" style="display:none">准备发布</span>
            <span class="zh-TW" style="display:none">準備發佈</span>
          </a></li>
      <li><a href="../../../guide/publishing/publishing.html">
            <span class="en">Publishing on Android Market</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Best Practices</span>
               <span class="de" style="display:none">Bewährte Verfahren</span>
               <span class="es" style="display:none">Prácticas recomendadas</span>
               <span class="fr" style="display:none">Meilleures pratiques</span>
               <span class="it" style="display:none">Best practice</span>
               <span class="ja" style="display:none">ベスト プラクティス</span>
               <span class="zh-CN" style="display:none">最佳实践</span>
               <span class="zh-TW" style="display:none">最佳實務</span>
    </h2>
    <ul>
      <li><a href="../../../guide/practices/compatibility.html">
            <span class="en">Compatibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/screens_support.html">
          <span class="en">Supporting Multiple Screens</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/practices/screens-distribution.html">
            <span class="en">Distributing to Specific Screens</span>
          </a></li>
          <li><a href="../../../guide/practices/screen-compat-mode.html">
            <span class="en">Screen Compatibility Mode</span>
          </a></li>
          <li><a href="../../../guide/practices/screens-support-1.5.html">
            <span class="en">Strategies for Android 1.5</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/optimizing-for-3.0.html">
            <span class="en">Optimizing Apps for Android 3.0</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/ui_guidelines/index.html">
               <span class="en">UI Guidelines</span>
             </a></div>
        <ul>
          <li class="toggle-list">
            <div><a href="../../../guide/practices/ui_guidelines/icon_design.html">
                   <span class="en">Icon Design <span class="new">updated</span></span>
                 </a></div>
            <ul>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html">
                    <span class="en">Launcher Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html">
                    <span class="en">Menu Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html">
                    <span class="en">Action Bar Icons <span class="new">new!</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html">
                    <span class="en">Status Bar Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html">
                    <span class="en">Tab Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html">
                    <span class="en">Dialog Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html">
                    <span class="en">List View Icons</span>
                  </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/practices/ui_guidelines/widget_design.html">
                <span class="en">App Widget Design <span class="new">updated</span></span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/activity_task_design.html">
                <span class="en">Activity and Task Design</span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/menu_design.html">
                <span class="en">Menu Design</span>
              </a></li>
        </ul>
      </li>
      </ul>
      <ul>
      <li><a href="../../../guide/practices/design/accessibility.html">
            <span class="en">Designing for Accessibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/design/performance.html">
            <span class="en">Designing for Performance</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/practices/design/jni.html">
                <span class="en">JNI Tips</span>
              </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/design/responsiveness.html">
            <span class="en">Designing for Responsiveness</span>
          </a></li>
      <li><a href="../../../guide/practices/design/seamlessness.html">
            <span class="en">Designing for Seamlessness</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Web Applications</span>
    </h2>
    <ul>
      <li><a href="../../../guide/webapps/index.html">
            <span class="en">Web Apps Overview</span>
          </a></li>
      <li><a href="../../../guide/webapps/targeting.html">
            <span class="en">Targeting Screens from Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/webview.html">
            <span class="en">Building Web Apps in WebView</span>
          </a></li>
      <li><a href="../../../guide/webapps/debugging.html">
            <span class="en">Debugging Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/best-practices.html">
            <span class="en">Best Practices for Web Apps</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Appendix</span>
               <span class="de" style="display:none">Anhang</span>
               <span class="es" style="display:none">Apéndice</span>
               <span class="fr" style="display:none">Annexes</span>
               <span class="it" style="display:none">Appendice</span>
               <span class="ja" style="display:none">付録</span>
               <span class="zh-CN" style="display:none">附录</span>
               <span class="zh-TW" style="display:none">附錄</span>
    </h2>
    <ul>
      <li><a href="../../../guide/appendix/api-levels.html">
            <span class="en">Android API Levels</span>
          </a></li>
      <li><a href="../../../guide/appendix/install-location.html">
            <span class="en">App Install Location</span>
          </a></li>
      <li><a href="../../../guide/appendix/media-formats.html">
            <span class="en">Supported Media Formats <span class="new">updated</span></span>
          </a></li>
      <li><a href="../../../guide/appendix/g-app-intents.html">
            <span class="en">Intents List: Google Apps</span>
          </a></li>
      <li><a href="../../../guide/developing/tools/aidl.html">AIDL</a></li>
      <li><a href="../../../guide/appendix/glossary.html">
            <span class="en">Glossary</span>
          </a></li>
    </ul>
  </li>

</ul>

<script type="text/javascript">
<!--
    buildToggleLists();
    changeNavLang(getLangPref());
//-->
</script>

      </div>
    </div> <!-- end side-nav -->
    <script>
      addLoadEvent(function() {
        scrollIntoView("devdoc-nav");
        });
    </script>




<div class="g-unit" id="doc-content"><a name="top"></a>

<div id="jd-header" class="guide-header">
  <span class="crumb">
    &nbsp;
    
  </span>
<h1>Services</h1>
</div>

  <div id="jd-content">

    <div class="jd-descr">
    <div id="qv-wrapper">
<ol id="qv">
<h2>Quickview</h2>
<ul>
  <li>A service can run in the background to perform work even while the user is in a different
application</li>
  <li>A service can allow other components to bind to it, in order to interact with it and
perform interprocess communication</li>
  <li>A service runs in the main thread of the application that hosts it, by default</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#Basics">The Basics</a></li>
<ol>
  <li><a href="#Declaring">Declaring a service in the manifest</a></li>
</ol>
<li><a href="#CreatingAService">Creating a Started Service</a>
  <ol>
    <li><a href="#ExtendingIntentService">Extending the IntentService class</a></li>
    <li><a href="#ExtendingService">Extending the Service class</a></li>
    <li><a href="#StartingAService">Starting a service</a></li>
    <li><a href="#Stopping">Stopping a service</a></li>
  </ol>
</li>
<li><a href="#CreatingBoundService">Creating a Bound Service</a></li>
<li><a href="#Notifications">Sending Notifications to the User</a></li>
<li><a href="#Foreground">Running a Service in the Foreground</a></li>
<li><a href="#Lifecycle">Managing the Lifecycle of a Service</a>
<ol>
  <li><a href="#LifecycleCallbacks">Implementing the lifecycle callbacks</a></li>
</ol>
</li>
</ol>

<h2>Key classes</h2>
<ol>
  <li><code><a href="../../../reference/android/app/Service.html">Service</a></code></li>
  <li><code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code></li>
</ol>

<h2>Samples</h2>
<ol>
  <li><a href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/ServiceStartArguments.html"><code>ServiceStartArguments</code></a></li>
  <li><a href="../../../resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html"><code>LocalService</code></a></li>
</ol>

<h2>Articles</h2>
<ol>
  <li><a href="../../../resources/articles/multitasking-android-way.html">Multitasking the Android Way</a></li>
  <li><a href="../../../resources/articles/service-api-changes-starting-with.html">Service API changes starting
      with Android 2.0</a></li>
</ol>

<h2>See also</h2>
<ol>
<li><a href="../../../guide/topics/fundamentals/bound-services.html">Bound Services</a></li>
</ol>

</div>


<p>A <code><a href="../../../reference/android/app/Service.html">Service</a></code> is an application component that can perform
long-running operations in the background and does not provide a user interface. Another
application component can start a service and it will continue to run in the background even if the
user switches to another application. Additionally, a component can bind to a service to
interact with it and even perform interprocess communication (IPC). For example, a service might
handle network transactions, play music, perform file I/O, or interact with a content provider, all
from the background.</p>
<p>Service是一个长期运行于后台并不提供UI的组件。一个应用程序可以启动一个service，即使用户切换到其它应用程序，它也会继续在后台运行。一个组件可以绑定一个service进行交互，甚至进行进程间的通信。比如说，一个service可能在处理网络事务，播放音乐，执行文件I/O或者与一个content provider相互作用，所有的都在后台进行。</p>

<p>A service can essentially take two forms:</p>
<p>两张形态:</p>

<dl>
  <dt>Started</dt>
  <dd>A service is "started" when an application component (such as an activity) starts it by
calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. Once started, a service
can run in the background indefinitely, even if the component that started it is destroyed. Usually,
a started service performs a single operation and does not return a result to the caller.
For example, it might download or upload a file over the network. When the operation is done, the
service should stop itself.
<p>一个组件使用startService()开始一个service，一旦开始，它就会一直在后台运行，即使开始它的组件已经被销毁。通常，一个被启动的service执行一个单一的操作，并且不返回数据给启动者。比如，下载或者上传文件完成后，这个service就自动停止了。</p></dd>
  <dt>Bound</dt>
  <dd>A service is "bound" when an application component binds to it by calling <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>. A bound service offers a client-server
interface that allows components to interact with the service, send requests, get results, and even
do so across processes with interprocess communication (IPC). A bound service runs only as long as
another application component is bound to it. Multiple components can bind to the service at once,
but when all of them unbind, the service is destroyed.
<p>当一个应用程序组件通过调用bindService()绑定到它上面时，这个service就是”bound”。一个绑定的service提供了一个客户-服务接口来允许这个组件与service交互，发送请求，获得结果甚至使用进程间通信来跨进程做这些。一个绑定的service一直运行直到有其他的组件绑定到它上面。多个组件可以一次性绑定到一个service，但是当它们都解除绑定时，service将被销毁。</p></dd>
</dl>

<p>Although this documentation generally discusses these two types of services separately, your
service can work both ways&mdash;it can be started (to run indefinitely) and also allow binding.
It's simply a matter of whether you implement a couple callback methods: <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> to allow components to start it and <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code> to allow binding.</p>
<p>虽然本文档分开讨论者两个形态，但是你的service可以同时处于这两个形态。它可以被启动(无限期运行)并且可以被绑定。只取决于你是否实现了一对回调函数：onStartCommand()来允许组件启动它以及onBind()允许绑定。</p>

<p>Regardless of whether your application is started, bound, or both, any application component
can use the service (even from a separate application), in the same way that any component can use
an activity&mdash;by starting it with an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code>. However, you can declare
the service as private, in the manifest file, and block access from other applications. This is
discussed more in the section about <a href="#Declaring">Declaring the service in the
manifest</a>.</p>
<p>不管你的那个程序启动它，绑定它，或者一起，任何其他的程序组件都可以使用这个service（即使是其他程序），就像任何组件都可以通过Intent启动和使用activity一样。不管怎么样，你也可以通过manifest文件把service定义为私有的。</p>

<p class="caution"><strong>Caution:</strong> A service runs in the
main thread of its hosting process&mdash;the service does <strong>not</strong> create its own thread
and does <strong>not</strong> run in a separate process (unless you specify otherwise). This means
that, if your service is going to do any CPU intensive work or blocking operations (such as MP3
playback or networking), you should create a new thread within the service to do that work. By using
a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the
application's main thread can remain dedicated to user interaction with your activities.</p>
<p class="caution"><strong>Caution:</strong>一个service运行于程序的主进程中---service不会创建它自己的线程并且不会运行在单独的进程（除非用别的方法指定）。这意味着，如果你的service将做一些CPU密集工作或者模块化的操作（比如MP3重放或联网）,你应该为service创建一个新的线程来做这些工作。通过使用单独的线程，你可以减少Application Not Responding (ANR)错误的风险并且应用程序的主线程可以依然专注于用户与你的activity的交互。</p>

<h2 id="Basics">The Basics</h2>

<div class="sidebox-wrapper">
<div class="sidebox">
  <h3>Should you use a service or a thread?</h3>
  <p>A service is simply a component that can run in the background even when the user is not
interacting with your application. Thus, you should create a service only if that is what you
need.</p>
  <p>If you need to perform work outside your main thread, but only while the user is interacting
with your application, then you should probably instead create a new thread and not a service. For
example, if you want to play some music, but only while your activity is running, you might create
a thread in <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>, start running it in <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code>, then stop it in <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code>. Also consider using <code><a href="../../../reference/android/os/AsyncTask.html">AsyncTask</a></code> or <code><a href="../../../reference/android/os/HandlerThread.html">HandlerThread</a></code>,
instead of the traditional <code><a href="../../../reference/java/lang/Thread.html">Thread</a></code> class. See the <a
href="../../../guide/topics/fundamentals/processes-and-threads.html#Threads">Processes and
Threading</a> document for more information about threads.</p>
  <p>Remember that if you do use a service, it still runs in your application's main thread by
default, so you should still create a new thread within the service if it performs intensive or
blocking operations.</p>
</div>
</div>

<p>To create a service, you must create a subclass of <code><a href="../../../reference/android/app/Service.html">Service</a></code> (or one
of its existing subclasses). In your implementation, you need to override some callback methods that
handle key aspects of the service lifecycle and provide a mechanism for components to bind to
the service, if appropriate. The most important callback methods you should override are:</p>

<dl>
  <dt><code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code></dt>
    <dd>The system calls this method when another component, such as an activity,
requests that the service be started, by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. Once this method executes, the service is started and can run in the
background indefinitely. If you implement this, it is your responsibility to stop the service when
its work is done, by calling <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>. (If you only want to provide binding, you don't
need to implement this method.)</dd>
  <dt><code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code></dt>
    <dd>The system calls this method when another component wants to bind with the
service (such as to perform RPC), by calling <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>. In your implementation of this method, you must provide an interface that clients
use to communicate with the service, by returning an <code><a href="../../../reference/android/os/IBinder.html">IBinder</a></code>. You must always
implement this method, but if you don't want to allow binding, then you should return null.</dd>
  <dt><code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code></dt>
    <dd>The system calls this method when the service is first created, to perform one-time setup
procedures (before it calls either <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> or
<code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code>). If the service is already running, this method is not
called.</dd>
  <dt><code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code></dt>
    <dd>The system calls this method when the service is no longer used and is being destroyed.
Your service should implement this to clean up any resources such as threads, registered
listeners, receivers, etc. This is the last call the service receives.</dd>
</dl>

<p>If a component starts the service by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> (which results in a call to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>), then the service
remains running until it stops itself with <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or another
component stops it by calling <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>.</p>

<p>If a component calls
<code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code> to create the service (and <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> is <em>not</em> called), then the service runs
only as long as the component is bound to it. Once the service is unbound from all clients, the
system destroys it.</p>

<p>The Android system will force-stop a service only when memory is low and it must recover system
resources for the activity that has user focus. If the service is bound to an activity that has user
focus, then it's less likely to be killed, and if the service is declared to <a
href="#Foreground">run in the foreground</a> (discussed later), then it will almost never be killed.
Otherwise, if the service was started and is long-running, then the system will lower its position
in the list of background tasks over time and the service will become highly susceptible to
killing&mdash;if your service is started, then you must design it to gracefully handle restarts
by the system. If the system kills your service, it restarts it as soon as resources become
available again (though this also depends on the value you return from <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>, as discussed later). For more information
about when the system might destroy a service, see the <a
href="../../../guide/topics/fundamentals/processes-and-threads.html">Processes and Threading</a>
document.</p>

<p>In the following sections, you'll see how you can create each type of service and how to use
it from other application components.</p>



<h3 id="Declaring">Declaring a service in the manifest</h3>

<p>Like activities (and other components), you must declare all services in your application's
manifest file.</p>

<p>To declare your service, add a <a
href="../../../guide/topics/manifest/service-element.html"><code>&lt;service&gt;</code></a> element
as a child of the <a
href="../../../guide/topics/manifest/application-element.html"><code>&lt;application&gt;</code></a>
element. For example:</p>

<pre>
&lt;manifest ... &gt;
  ...
  &lt;application ... &gt;
      &lt;service android:name=".ExampleService" /&gt;
      ...
  &lt;/application&gt;
&lt;/manifest&gt;
</pre>

<p>There are other attributes you can include in the <a
href="../../../guide/topics/manifest/service-element.html"><code>&lt;service&gt;</code></a> element to
define properties such as permissions required to start the service and the process in
which the service should run. The <a
href="../../../guide/topics/manifest/service-element.html#nm"><code>android:name</code></a>
attribute is the only required attribute&mdash;it specifies the class name of the service. Once
you publish your application, you should not change this name, because if you do, you might break
some functionality where explicit intents are used to reference your service (read the blog post, <a
href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things
That Cannot Change</a>).

<p>See the <a
href="../../../guide/topics/manifest/service-element.html"><code>&lt;service&gt;</code></a> element
reference for more information about declaring your service in the manifest.</p>

<p>Just like an activity, a service can define intent filters that allow other components to
invoke the service using implicit intents. By declaring intent filters, components
from any application installed on the user's device can potentially start your service if your
service declares an intent filter that matches the intent another application passes to <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>.</p>

<p>If you plan on using your service only locally (other applications do not use it), then you
don't need to (and should not) supply any intent filters. Without any intent filters, you must
start the service using an intent that explicitly names the service class. More information
about <a href="#StartingAService">starting a service</a> is discussed below.</p>

<p>Additionally, you can ensure that your service is private to your application only if
you include the <a
href="../../../guide/topics/manifest/service-element.html#exported"><code>android:exported</code></a>
attribute and set it to <code>"false"</code>. This is effective even if your service supplies intent
filters.</p>

<p>For more information about creating intent filters for your service, see the <a
href="../../../guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>
document.</p>



<h2 id="CreatingStartedService">Creating a Started Service</h2>

<div class="sidebox-wrapper">
<div class="sidebox">
  <h2>Targeting Android 1.6 or lower</h2>
  <p>If you're building an application for Android 1.6 or lower, you need
to implement <code><a href="../../../reference/android/app/Service.html#onStart(android.content.Intent, int)">onStart()</a></code>, instead of <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> (in Android 2.0,
<code><a href="../../../reference/android/app/Service.html#onStart(android.content.Intent, int)">onStart()</a></code> was deprecated in favor of <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>).</p>
  <p>For more information about providing compatibility with versions of Android older than 2.0, see
the <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> documentation.</p>
</div>
</div>

<p>A started service is one that another component starts by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>, resulting in a call to the service's
<code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> method.</p>

<p>When a service is started, it has a lifecycle that's independent of the
component that started it and the service can run in the background indefinitely, even if
the component that started it is destroyed. As such, the service should stop itself when its job
is done by calling <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code>, or another component can stop it
by calling <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>.</p>

<p>An application component such as an activity can start the service by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> and passing an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code>
that specifies the service and includes any data for the service to use. The service receives
this <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> in the <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> method.</p>

<p>For instance, suppose an activity needs to save some data to an online database. The activity can
start a companion service and deliver it the data to save by passing an intent to <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. The service receives the intent in <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>, connects to the Internet and performs the
database transaction. When the transaction is done, the service stops itself and it is
destroyed.</p>

<p class="caution"><strong>Caution:</strong> A services runs in the same process as the application
in which it is declared and in the main thread of that application, by default. So, if your service
performs intensive or blocking operations while the user interacts with an activity from the same
application, the service will slow down activity performance. To avoid impacting application
performance, you should start a new thread inside the service.</p>

<p>Traditionally, there are two classes you can extend to create a started service:</p>
<dl>
  <dt><code><a href="../../../reference/android/app/Service.html">Service</a></code></dt>
  <dd>This is the base class for all services. When you extend this class, it's important that
you create a new thread in which to do all the service's work, because the service uses your
application's main thread, by default, which could slow the performance of any activity your
application is running.</dd>
  <dt><code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code></dt>
  <dd>This is a subclass of <code><a href="../../../reference/android/app/Service.html">Service</a></code> that uses a worker thread to handle all
start requests, one at a time. This is the best option if you don't require that your service
handle multiple requests simultaneously. All you need to do is implement <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code>, which receives the intent for each
start request so you can do the background work.</dd>
</dl>

<p>The following sections describe how you can implement your service using either one for these
classes.</p>


<h3 id="ExtendingIntentService">Extending the IntentService class</h3>

<p>Because most started services don't need to handle multiple requests simultaneously
(which can actually be a dangerous multi-threading scenario), it's probably best if you
implement your service using the <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code> class.</p>

<p>The <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code> does the following:</p>

<ul>
  <li>Creates a default worker thread that executes all intents delivered to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> separate from your application's main
thread.</li>
  <li>Creates a work queue that passes one intent at a time to your <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code> implementation, so you never have to
worry about multi-threading.</li>
  <li>Stops the service after all start requests have been handled, so you never have to call
<code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code>.</li>
  <li>Provides default implementation of <code><a href="../../../reference/android/app/IntentService.html#onBind(android.content.Intent)">onBind()</a></code> that
returns null.</li>
  <li>Provides a default implementation of <code><a href="../../../reference/android/app/IntentService.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> that sends the intent to the work queue and then to your <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code> implementation.</li>
</ul>

<p>All this adds up to the fact that all you need to do is implement <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code> to do the work provided by the
client. (Though, you also need to provide a small constructor for the service.)</p>

<p>Here's an example implementation of <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code>:</p>

<pre>
public class HelloIntentService extends IntentService {

  /** 
   * A constructor is required, and must call the super <code><a href="../../../reference/android/app/IntentService.html#IntentService(java.lang.String)">IntentService(String)</a></code>
   * constructor with a name for the worker thread.
   */
  public HelloIntentService() {
      super("HelloIntentService");
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  &#64;Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
      // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() &lt; endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }
}
</pre>

<p>That's all you need: a constructor and an implementation of <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code>.</p>

<p>If you decide to also override other callback methods, such as <code><a href="../../../reference/android/app/IntentService.html#onCreate()">onCreate()</a></code>, <code><a href="../../../reference/android/app/IntentService.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>, or <code><a href="../../../reference/android/app/IntentService.html#onDestroy()">onDestroy()</a></code>, be sure to call the super implementation, so
that the <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code> can properly handle the life of the worker thread.</p>

<p>For example, <code><a href="../../../reference/android/app/IntentService.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> must return
the default implementation (which is how the intent gets delivered to <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code>):</p>

<pre>
&#64;Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}
</pre>

<p>Besides <code><a href="../../../reference/android/app/IntentService.html#onHandleIntent(android.content.Intent)">onHandleIntent()</a></code>, the only method
from which you don't need to call the super class is <code><a href="../../../reference/android/app/IntentService.html#onBind(android.content.Intent)">onBind()</a></code> (but you only need to implement that if your service allows binding).</p>

<p>In the next section, you'll see how the same kind of service is implemented when extending
the base <code><a href="../../../reference/android/app/Service.html">Service</a></code> class, which is a lot more code, but which might be
appropriate if you need to handle simultaneous start requests.</p>


<h3 id="ExtendingService">Extending the Service class</h3>

<p>As you saw in the previous section, using <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code> makes your
implementation of a started service very simple. If, however, you require your service to
perform multi-threading (instead of processing start requests through a work queue), then you
can extend the <code><a href="../../../reference/android/app/Service.html">Service</a></code> class to handle each intent.</p>

<p>For comparison, the following example code is an implementation of the <code><a href="../../../reference/android/app/Service.html">Service</a></code> class that performs the exact same work as the example above using <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code>. That is, for each start request, it uses a worker thread to perform the
job and processes only one request at a time.</p>

<pre>
public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
      &#64;Override
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() &lt; endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  &#64;Override
  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    
    // Get the HandlerThread's Looper and use it for our Handler 
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  &#64;Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      
      // If we get killed, after returning from here, restart
      return START_STICKY;
  }

  &#64;Override
  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }
  
  &#64;Override
  public void onDestroy() {
    Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show(); 
  }
}
</pre>

<p>As you can see, it's a lot more work than using <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code>.</p>

<p>However, because you handle each call to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> yourself, you can perform multiple requests simultaneously. That's not what
this example does, but if that's what you want, then you can create a new thread for each
request and run them right away (instead of waiting for the previous request to finish).</p>

<p>Notice that the <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> method must return an
integer. The integer is a value that describes how the system should continue the service in the
event that the system kills it (as discussed above, the default implementation for <code><a href="../../../reference/android/app/IntentService.html">IntentService</a></code> handles this for you, though you are able to modify it). The return value
from <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> must be one of the following
constants:</p>

<dl>
  <dt><code><a href="../../../reference/android/app/Service.html#START_NOT_STICKY">START_NOT_STICKY</a></code></dt>
    <dd>If the system kills the service after <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> returns, <em>do not</em> recreate the service, unless there are pending
intents to deliver. This is the safest option to avoid running your service when not necessary
and when your application can simply restart any unfinished jobs.</dd>
  <dt><code><a href="../../../reference/android/app/Service.html#START_STICKY">START_STICKY</a></code></dt>
    <dd>If the system kills the service after <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> returns, recreate the service and call <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>, but <em>do not</em> redeliver the last intent.
Instead, the system calls <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> with a
null intent, unless there were pending intents to start the service, in which case,
those intents are delivered. This is suitable for media players (or similar services) that are not
executing commands, but running indefinitely and waiting for a job.</dd>
  <dt><code><a href="../../../reference/android/app/Service.html#START_REDELIVER_INTENT">START_REDELIVER_INTENT</a></code></dt>
    <dd>If the system kills the service after <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> returns, recreate the service and call <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> with the last intent that was delivered to the
service. Any pending intents are delivered in turn. This is suitable for services that are
actively performing a job that should be immediately resumed, such as downloading a file.</dd>
</dl>
<p>For more details about these return values, see the linked reference documentation for each
constant.</p>



<h3 id="StartingAService">Starting a Service</h3>

<p>You can start a service from an activity or other application component by passing an
<code><a href="../../../reference/android/content/Intent.html">Intent</a></code> (specifying the service to start) to <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. The Android system calls the service's <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> method and passes it the <code><a href="../../../reference/android/content/Intent.html">Intent</a></code>. (You should never call <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> directly.)</p>

<p>For example, an activity can start the example service in the previous section (<code>HelloSevice</code>) using an explicit intent with <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>:</p>

<pre>
Intent intent = new Intent(this, HelloService.class);
startService(intent);
</pre>

<p>The <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> method returns immediately and
the Android system calls the service's <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> method. If the service is not already running, the system first calls <code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code>, then calls <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>.</p>

<p>If the service does not also provide binding, the intent delivered with <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> is the only mode of communication between the
application component and the service. However, if you want the service to send a result back, then
the client that starts the service can create a <code><a href="../../../reference/android/app/PendingIntent.html">PendingIntent</a></code> for a broadcast
(with <code><a href="../../../reference/android/app/PendingIntent.html#getBroadcast(android.content.Context, int, android.content.Intent, int)">getBroadcast()</a></code>) and deliver it to the service
in the <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> that starts the service. The service can then use the
broadcast to deliver a result.</p>

<p>Multiple requests to start the service result in multiple corresponding calls to the service's
<code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>. However, only one request to stop
the service (with <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>) is required to stop it.</p>


<h3 id="Stopping">Stopping a service</h3>

<p>A started service must manage its own lifecycle. That is, the system does not stop or
destroy the service unless it must recover system memory and the service
continues to run after <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> returns. So,
the service must stop itself by calling <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or another
component can stop it by calling <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>.</p>

<p>Once requested to stop with <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>, the system destroys the service as soon as
possible.</p>

<p>However, if your service handles multiple requests to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> concurrently, then you shouldn't stop the
service when you're done processing a start request, because you might have since received a new
start request (stopping at the end of the first request would terminate the second one). To avoid
this problem, you can use <code><a href="../../../reference/android/app/Service.html#stopSelf(int)">stopSelf(int)</a></code> to ensure that your request to
stop the service is always based on the most recent start request. That is, when you call <code><a href="../../../reference/android/app/Service.html#stopSelf(int)">stopSelf(int)</a></code>, you pass the ID of the start request (the <code>startId</code>
delivered to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>) to which your stop request
corresponds. Then if the service received a new start request before you were able to call <code><a href="../../../reference/android/app/Service.html#stopSelf(int)">stopSelf(int)</a></code>, then the ID will not match and the service will not stop.</p>

<p class="caution"><strong>Caution:</strong> It's important that your application stops its services
when it's done working, to avoid wasting system resources and consuming battery power. If necessary,
other components can stop the service by calling <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>. Even if you enable binding for the service,
you must always stop the service yourself if it ever received a call to <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>.</p>

<p>For more information about the lifecycle of a service, see the section below about <a
href="#Lifecycle">Managing the Lifecycle of a Service</a>.</p>



<h2 id="CreatingBoundService">Creating a Bound Service</h2>

<p>A bound service is one that allows application components to bind to it by calling <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code> in order to create a long-standing connection
(and generally does not allow components to <em>start</em> it by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>).</p>

<p>You should create a bound service when you want to interact with the service from activities
and other components in your application or to expose some of your application's functionality to
other applications, through interprocess communication (IPC).</p>

<p>To create a bound service, you must implement the <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code> callback method to return an <code><a href="../../../reference/android/os/IBinder.html">IBinder</a></code> that
defines the interface for communication with the service. Other application components can then call
<code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code> to retrieve the interface and
begin calling methods on the service. The service lives only to serve the application component that
is bound to it, so when there are no components bound to the service, the system destroys it
(you do <em>not</em> need to stop a bound service in the way you must when the service is started
through <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code>).</p>

<p>To create a bound service, the first thing you must do is define the interface that specifies
how a client can communicate with the service. This interface between the service
and a client must be an implementation of <code><a href="../../../reference/android/os/IBinder.html">IBinder</a></code> and is what your service must
return from the <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code> callback method. Once the client receives the <code><a href="../../../reference/android/os/IBinder.html">IBinder</a></code>, it can begin
interacting with the service through that interface.</p>

<p>Multiple clients can bind to the service at once. When a client is done interacting with the
service, it calls <code><a href="../../../reference/android/content/Context.html#unbindService(android.content.ServiceConnection)">unbindService()</a></code> to unbind. Once
there are no clients bound to the service, the system destroys the service.</p>

<p>There are multiple ways to implement a bound service and the implementation is more
complicated than a started service, so the bound service discussion appears in a separate
document about <a
href="../../../guide/topics/fundamentals/bound-services.html">Bound Services</a>.</p>



<h2 id="Notifications">Sending Notifications to the User</h2>

<p>Once running, a service can notify the user of events using <a
href="../../../guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a
href="../../../guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>.</p>

<p>A toast notification is a message that appears on the surface of the current window for a
moment then disappears, while a status bar notification provides an icon in the status bar with a
message, which the user can select in order to take an action (such as start an activity).</p>

<p>Usually, a status bar notification is the best technique when some background work has completed
(such as a file completed
downloading) and the user can now act on it. When the user selects the notification from the
expanded view, the notification can start an activity (such as to view the downloaded file).</p>

<p>See the <a
href="../../../guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> or <a
href="../../../guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
developer guides for more information.</p>



<h2 id="Foreground">Running a Service in the Foreground</h2>

<p>A foreground service is a service that's considered to be something the
user is actively aware of and thus not a candidate for the system to kill when low on memory. A 
foreground service must provide a notification for the status bar, which is placed under the
"Ongoing" heading, which means that the notification cannot be dismissed unless the service is
either stopped or removed from the foreground.</p>

<p>For example, a music player that plays music from a service should be set to run in the
foreground, because the user is explicitly aware
of its operation. The notification in the status bar might indicate the current song and allow
the user to launch an activity to interact with the music player.</p>

<p>To request that your service run in the foreground, call <code><a href="../../../reference/android/app/Service.html#startForeground(int, android.app.Notification)">startForeground()</a></code>. This method takes two parameters: an integer
that uniquely identifies the notification and the <code><a href="../../../reference/android/app/Notification.html">Notification</a></code> for the status bar. For example:</p>

<pre>
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);
</pre>


<p>To remove the service from the foreground, call <code><a href="../../../reference/android/app/Service.html#stopForeground(boolean)">stopForeground()</a></code>. This method takes a boolean, indicating
whether to remove the status bar notification as well. This method does <em>not</em> stop the
service. However, if you stop the service while it's still running in the foreground, then the
notification is also removed.</p>

<p class="note"><strong>Note:</strong> The methods <code><a href="../../../reference/android/app/Service.html#startForeground(int, android.app.Notification)">startForeground()</a></code> and <code><a href="../../../reference/android/app/Service.html#stopForeground(boolean)">stopForeground()</a></code> were introduced in Android 2.0 (API Level
5). In order to run your service in the foreground on older versions of the platform, you must
use the previous <code>setForeground()</code> method&mdash;see the <code><a href="../../../reference/android/app/Service.html#startForeground(int, android.app.Notification)">startForeground()</a></code> documentation for information about how
to provide backward compatibility.</p>

<p>For more information about notifications, see <a
href="../../../guide/topics/ui/notifiers/notifications.html">Creating Status Bar
Notifications</a>.</p>



<h2 id="Lifecycle">Managing the Lifecycle of a Service</h2>

<p>The lifecycle of a service is much simpler than that of an activity. However, it's even more important
that you pay close attention to how your service is created and destroyed, because a service
can run in the background without the user being aware.</p>

<p>The service lifecycle&mdash;from when it's created to when it's destroyed&mdash;can follow two
different paths:</p>

<ul>
<li>A started service
  <p>The service is created when another component calls <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. The service then runs indefinitely and must
stop itself by calling <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code>. Another component can also stop the
service by calling <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>. When the service is stopped, the system destroys it..</p></li>

<li>A bound service
  <p>The service is created when another component (a client) calls <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>. The client then communicates with the service
through an <code><a href="../../../reference/android/os/IBinder.html">IBinder</a></code> interface. The client can close the connection by calling
<code><a href="../../../reference/android/content/Context.html#unbindService(android.content.ServiceConnection)">unbindService()</a></code>. Multiple clients can bind to
the same service and when all of them unbind, the system destroys the service. (The service
does <em>not</em> need to stop itself.)</p></li>
</ul>

<p>These two paths are not entirely separate. That is, you can bind to a service that was already
started with <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>. For example, a background
music service could be started by calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> with an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> that identifies the music to play. Later,
possibly when the user wants to exercise some control over the player or get information about the
current song, an activity can bind to the service by calling <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>. In cases like this, <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code> or <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> does not actually stop the service until all clients unbind. </p>


<h3 id="LifecycleCallbacks">Implementing the lifecycle callbacks</h3>

<p>Like an activity, a service has lifecycle callback methods that you can implement to monitor
changes in the service's state and perform work at the appropriate times. The following skeleton
service demonstrates each of the lifecycle methods:</p>


<div class="figure" style="width:432px">
<img src="../../../images/service_lifecycle.png" alt="" />
<p class="img-caption"><strong>Figure 2.</strong> The service lifecycle. The diagram on the left
shows the lifecycle when the service is created with <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> and the diagram on the right shows the lifecycle when the service is created
with <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>.</p>
</div>

<pre>
public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    &#64;Override
    public void <code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate</a></code>() {
        // The service is being created
    }
    &#64;Override
    public int <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand</a></code>(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>
        return <em>mStartMode</em>;
    }
    &#64;Override
    public IBinder <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind</a></code>(Intent intent) {
        // A client is binding to the service with <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>
        return <em>mBinder</em>;
    }
    &#64;Override
    public boolean <code><a href="../../../reference/android/app/Service.html#onUnbind(android.content.Intent)">onUnbind</a></code>(Intent intent) {
        // All clients have unbound with <code><a href="../../../reference/android/content/Context.html#unbindService(android.content.ServiceConnection)">unbindService()</a></code>
        return <em>mAllowRebind</em>;
    }
    &#64;Override
    public void <code><a href="../../../reference/android/app/Service.html#onRebind(android.content.Intent)">onRebind</a></code>(Intent intent) {
        // A client is binding to the service with <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>,
        // after onUnbind() has already been called
    }
    &#64;Override
    public void <code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy</a></code>() {
        // The service is no longer used and is being destroyed
    }
}
</pre>

<p class="note"><strong>Note:</strong> Unlike the activity lifecycle callback methods, you are
<em>not</em> required to call the superclass implementation of these callback methods.</p>

<p>By implementing these methods, you can monitor two nested loops of the service's lifecycle: </p>

<ul>
<li>The <strong>entire lifetime</strong> of a service happens between the time <code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code> is called and the time <code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code> returns. Like an activity, a service does its initial setup in
<code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code> and releases all remaining resources in <code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code>.  For example, a
music playback service could create the thread where the music will be played in <code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code>, then stop the thread in <code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code>.

<p>The <code><a href="../../../reference/android/app/Service.html#onCreate()">onCreate()</a></code> and <code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code> methods are called for all services, whether
they're created by <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> or <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>.</p></li>

<li>The <strong>active lifetime</strong> of a service begins with a call to either <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> or <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code>.
Each method is handed the <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> that was passed to either <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> or <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>, respectively.
<p>If the service is started, the active lifetime ends the same time that the entire lifetime
ends (the service is still active even after <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> returns). If the service is bound, the active lifetime ends when <code><a href="../../../reference/android/app/Service.html#onUnbind(android.content.Intent)">onUnbind()</a></code> returns.</p>
</li>
</ul>

<p class="note"><strong>Note:</strong> Although a started service is stopped by a call to
either <code><a href="../../../reference/android/app/Service.html#stopSelf()">stopSelf()</a></code> or <code><a href="../../../reference/android/content/Context.html#stopService(android.content.Intent)">stopService()</a></code>, there is not a respective callback for the
service (there's no <code>onStop()</code> callback). So, unless the service is bound to a client,
the system destroys it when the service is stopped&mdash;<code><a href="../../../reference/android/app/Service.html#onDestroy()">onDestroy()</a></code> is the only callback received.</p>

<p>Figure 2 illustrates the typical callback methods for a service. Although the figure separates
services that are created by <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code> from those
created by <code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>, keep
in mind that any service, no matter how it's started, can potentially allow clients to bind to it.
So, a service that was initially started with <code><a href="../../../reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)">onStartCommand()</a></code> (by a client calling <code><a href="../../../reference/android/content/Context.html#startService(android.content.Intent)">startService()</a></code>)
can still receive a call to <code><a href="../../../reference/android/app/Service.html#onBind(android.content.Intent)">onBind()</a></code> (when a client calls
<code><a href="../../../reference/android/content/Context.html#bindService(android.content.Intent, android.content.ServiceConnection, int)">bindService()</a></code>).</p>

<p>For more information about creating a service that provides binding, see the <a
href="../../../guide/topics/fundamentals/bound-services.html">Bound Services</a> document,
which includes more information about the <code><a href="../../../reference/android/app/Service.html#onRebind(android.content.Intent)">onRebind()</a></code>
callback method in the section about <a
href="../../../guide/topics/fundamentals/bound-services.html#Lifecycle">Managing the Lifecycle of
a Bound Service</a>.</p>


<!--
<h2>Beginner's Path</h2>

<p>To learn how to query data from the system or other applications (such as contacts or media
stored on the device), continue with the <b><a
href="../../../guide/topics/providers/content-providers.html">Content Providers</a></b>
document.</p>
-->

    </div>

  <a href="#top" style="float:right">&uarr; Go to top</a>
  
  </div>

<div id="footer">


  <div id="copyright">
    
  Except as noted, this content is licensed under <a
  href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. 
  For details and restrictions, see the <a href="../../../license.html">
  Content License</a>.
  </div>
  <div id="build_info">
    
  Android 4.0&nbsp;r1 - 17 Oct 2011 18:17

  </div>

  <div id="footerlinks">
    
  <p>
    <a href="http://www.android.com/terms.html">Site Terms of Service</a> -
    <a href="http://www.android.com/privacy.html">Privacy Policy</a> -
    <a href="http://www.android.com/branding.html">Brand Guidelines</a>
  </p>
  </div>

</div> <!-- end footer -->

</div><!-- end doc-content -->

</div> <!-- end body-content --> 

<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>

</body>
</html>



